/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.HttpUtils;
import com.yami.shop.security.admin.dto.CaptchaAuthenticationDTO;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.enums.SysTypeEnum;
import com.yami.shop.security.common.manager.PasswordCheckManager;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.security.common.manager.TokenStore;
import com.yami.shop.security.common.vo.TokenInfoVO;
import com.yami.shop.sys.constant.Constant;
import com.yami.shop.sys.model.SysMenu;
import com.yami.shop.sys.model.SysUser;
import com.yami.shop.sys.service.SysMenuService;
import com.yami.shop.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author FrozenWatermelon
 * @date 2020/6/30
 */
@Controller
@Api(tags = "扫码登录")
@Slf4j
public class Oauth2LoginController {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private PasswordCheckManager passwordCheckManager;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private PasswordManager passwordManager;

    @Value("${ycl.weibo.client_id}")
    private String client_id;

    @Value("${ycl.weibo.client_secret}")
    private String client_secret;

    @Value("${ycl.weibo.redirect_uri}")
    private String redirect_uri;


    @GetMapping(value = "/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        log.info("进到这里");

        Map<String, String> map = new HashMap<>();
        map.put("client_id", client_id);
        map.put("client_secret", client_secret);
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", redirect_uri);
        map.put("code", code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            log.info("````````````````````````微博授权登陆成功");
            //获取到了access_token,转为通用社交登录对象
            String json = EntityUtils.toString(response.getEntity());
            //String json = JSON.toJSONString(response.getEntity());
            SysUser socialUser = JSON.parseObject(json, SysUser.class);
            System.out.println("socialUser = " + socialUser);
            SysUser sysUser = sysUserService.getByUid(socialUser.getUid());
            if (sysUser == null) {
                throw new YamiShopBindException("账号或密码不正确");
            }
            // 不是店铺超级管理员，并且是禁用状态，无法登录
            if (Objects.equals(sysUser.getStatus(), 0)) {
                // 未找到此用户信息
                throw new YamiShopBindException("未找到此用户信息");
            }

            UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();
            userInfoInToken.setUserId(String.valueOf(sysUser.getUserId()));
            userInfoInToken.setSysType(SysTypeEnum.ADMIN.value());
            userInfoInToken.setEnabled(sysUser.getStatus() == 1);
            userInfoInToken.setPerms(getUserPermissions(sysUser.getUserId()));
            userInfoInToken.setNickName(sysUser.getUsername());
            userInfoInToken.setShopId(sysUser.getShopId());
//            userInfoInToken.setUid(sysUser.getUid());
            // 存储token返回vo
            TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken);
//            return ResponseEntity.ok(tokenInfoVO);
            session.setAttribute("Authorization",tokenInfoVO.getAccessToken());
            log.info("token==="+tokenInfoVO.getAccessToken());
            return "redirect:http://localhost:9528/#/login?token="+tokenInfoVO.getAccessToken();

        } else {
            log.info("授权失败");
            return "授权失败";
        }
    }

    private Set<String> getUserPermissions(Long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if (userId == Constant.SUPER_ADMIN_ID) {
            List<SysMenu> menuList = sysMenuService.list(Wrappers.emptyWrapper());
            permsList = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
        } else {
            permsList = sysUserService.queryAllPerms(userId);
        }
        return permsList.stream().flatMap((perms) -> {
                    if (StrUtil.isBlank(perms)) {
                        return null;
                    }
                    return Arrays.stream(perms.trim().split(StrUtil.COMMA));
                }
        ).collect(Collectors.toSet());
    }
}
